package main

import (
	"dev-vpn-service/dev"
	"encoding/json"
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/gorm"
	"log"
	"net/http"
	"strconv"
)

func init() {
	viper.SetConfigName("config") // 配置文件名 (不带扩展名)
	viper.SetConfigType("yaml")   // 配置文件类型
	viper.AddConfigPath("dev")    // 配置文件所在的路径

	err := viper.ReadInConfig()
	if err != nil {
		log.Fatalf("无法读取配置文件: %v", err)
	}
}

func handleModifyConfig(db *gorm.DB, user dev.UserConfig) (string, error) {
	res, err := dev.CreateUser(db, user)
	if err != nil {
		log.Fatalf("创建用户失败: %v", err)
		return "创建用户失败", err
	}
	log.Println("创建用户成功", res)
	if err := dev.GenerateConfigForUser(user, db); err != nil {
		if err := dev.GenerateConfigForUser(user, db); err != nil {
			log.Println("生成配置失败: %v", err) //}og.Println("生成配置失败: %v", err)
			return "生成配置失败", err
		}
	}
	dev.RestartShadowsocks()
	return "配置生成成功", nil
}
func main() {
	db, err := dev.InitDB()
	if err != nil {
		log.Fatalf("无法初始化数据库: %v", err)
	}

	go dev.Fun(db) // 开始监控流量

	// 获取端口信息
	port := viper.GetString("server.port")
	log.Println("接口暴露地址", port)
	address := fmt.Sprintf(":%s", port)

	// 设置 HTTP 处理函数
	http.HandleFunc("/monitor", func(w http.ResponseWriter, r *http.Request) {
		var err error
		t := db.Begin()
		defer func() {
			if err != nil {
				t.Rollback()
			} else {
				t.Commit()
			}
		}()
		if r.Method == http.MethodPost {
			//jwt验证
			flag := viper.GetString("jwt.parse")
			if flag == "true" {
				jwt, err := dev.CheckJWT(w, r)
				if err != nil || !jwt {
					http.Error(w, "jwt校验失败", http.StatusBadRequest)
					return
				}
			}
			// 假设你从 POST 请求中接收用户信息，例如 JSON 格式
			var user dev.UserConfig
			// 从请求中解析用户信息 (此处简化处理，实际中需要验证输入数据)
			if err = json.NewDecoder(r.Body).Decode(&user); err != nil {
				http.Error(w, "无效的用户数据", http.StatusBadRequest)
				return
			}

			// 调用 handleModifyConfig 处理函数
			var message string
			message, err = handleModifyConfig(t, user)
			if err != nil {
				http.Error(w, err.Error(), http.StatusNotFound)
				return
			}

			_, err = fmt.Fprintln(w, message)
			if err != nil {
				return
			}
		} else {
			http.Error(w, "只支持 POST 请求", http.StatusMethodNotAllowed)
		}
	})

	//生成jwt秘钥
	http.HandleFunc("/generateJWT", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodPost {
			var jwt dev.JWTConfig
			if err := json.NewDecoder(r.Body).Decode(&jwt); err != nil {
				http.Error(w, "jwt数据校验失败", http.StatusBadRequest)
				return
			}
			generateJWT, err := dev.GenerateJWT(jwt.UserId, jwt.Username)
			if err != nil {
				return
			}
			_, err = fmt.Fprintln(w, generateJWT)
			if err != nil {
				return
			}
		} else {
			http.Error(w, "只支持 POST 请求", http.StatusMethodNotAllowed)
		}
	})

	//查看流量使用情况
	http.HandleFunc("/getFlowUsed", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodPost {
			//jwt验证
			flag := viper.GetString("jwt.parse")
			if flag == "true" {
				jwt, err := dev.CheckJWT(w, r)
				if err != nil || !jwt {
					http.Error(w, "jwt校验失败", http.StatusBadRequest)
					return
				}
			}

			var user dev.UserConfig
			// 从请求中解析用户信息 (此处简化处理，实际中需要验证输入数据)
			if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
				http.Error(w, "无效的用户数据", http.StatusBadRequest)
				return
			}

			user, err := dev.GetUserByUserId(db, strconv.Itoa(user.Id))
			log.Printf("user msg： %v", user)
			if err != nil {
				http.Error(w, "用户信息获取失败", http.StatusBadRequest)
				return
			}
			// 设置响应头为 JSON
			w.Header().Set("Content-Type", "application/json")
			if err := json.NewEncoder(w).Encode(user); err != nil {
				http.Error(w, "服务器内部错误", http.StatusInternalServerError)
			}
		} else {
			http.Error(w, "只支持 POST 请求", http.StatusMethodNotAllowed)
		}
	})

	//查看全部用户流量使用情况
	http.HandleFunc("/getAllFlowUsed", func(w http.ResponseWriter, r *http.Request) {
		//jwt验证
		flag := viper.GetString("jwt.parse")
		if flag == "true" {
			jwt, err := dev.CheckJWT(w, r)
			if err != nil || !jwt {
				http.Error(w, "jwt校验失败", http.StatusBadRequest)
				return
			}
		}
		users, err := dev.GetAllUser(db)
		if err != nil {
			http.Error(w, "获取用户信息失败", http.StatusInternalServerError)
			return
		}
		log.Printf("users msg: %v", users)
		w.Header().Set("Content-Type", "application/json")
		if err := json.NewEncoder(w).Encode(users); err != nil {
			http.Error(w, "服务器内部错误", http.StatusInternalServerError)
		}
	})

	//同步服务器文件与数据库文件
	http.HandleFunc("/syncDBAndService", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodPost {
			//jwt验证
			flag := viper.GetString("jwt.parse")
			if flag == "true" {
				jwt, err := dev.CheckJWT(w, r)
				if err != nil || !jwt {
					http.Error(w, "jwt校验失败", http.StatusBadRequest)
					return
				}
			}

			var user dev.UserConfig
			// 从请求中解析用户信息 (此处简化处理，实际中需要验证输入数据)
			if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
				http.Error(w, "无效的用户数据", http.StatusBadRequest)
				return
			}

			user, err := dev.GetUserByUserId(db, strconv.Itoa(user.Id))
			log.Printf("user msg： %v", user)
			if err != nil {
				http.Error(w, "用户信息获取失败", http.StatusBadRequest)
				return
			}
			// 设置响应头为 JSON
			w.Header().Set("Content-Type", "application/json")
			if err := json.NewEncoder(w).Encode(user); err != nil {
				http.Error(w, "服务器内部错误", http.StatusInternalServerError)
			}
		} else {
			http.Error(w, "只支持 POST 请求", http.StatusMethodNotAllowed)
		}
	})

	// 启动 HTTP 服务器，监听配置文件中的端口
	fmt.Printf("HTTP 服务器正在监听端口 %s\n", address)
	if err := http.ListenAndServe(address, nil); err != nil {
		log.Fatalf("无法启动服务器: %v", err)
	}
}
